package org.hbkj.springbootmybatis.controller;

import org.hbkj.springbootmybatis.entity.BuysDo;
import org.hbkj.springbootmybatis.service.BuysService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/test")
public class TestController {

    private final BuysService buysService;

    public TestController(BuysService buysService) {
        this.buysService = buysService;
    }

    /**
     * 测试立即购买接口
     */
    @PostMapping("/purchases")
    public ResponseEntity<Map<String, Object>> testPurchase(@RequestBody BuysDo buysDo) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 设置默认值（如果前端未提供）
            if (buysDo.getUserId() == null) {
                buysDo.setUserId(1); // 默认用户ID
            }

            if (buysDo.getOrderStatus() == null) {
                buysDo.setOrderStatus("待付款");
            }

            // 执行购买逻辑
            int rows = buysService.purchase(buysDo);

            if (rows > 0) {
                result.put("success", true);
                result.put("message", "测试购买成功");
                result.put("orderId", buysDo.getOrderId());
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "测试购买失败，可能库存不足");
                return ResponseEntity.status(400).body(result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统异常：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
}